package cn.serenedream.housedecoration.controller;

import cn.serenedream.housedecoration.dto.ProductWithModelDTO;
import cn.serenedream.housedecoration.entity.Products;
import cn.serenedream.housedecoration.serivce.ProductsService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("products")
public class ProductsController {
    @Autowired
    ProductsService productsService;

    @GetMapping("")
    public String list(@RequestParam(value = "current", required = false, defaultValue = "0") Integer currentPage,
                       @RequestParam(value = "page", required = false, defaultValue = "10") Integer pageSize,
                       @RequestParam(value = "name", required = false) String name,
                       Model model,
                       HttpServletRequest httpServletRequest) {
        Page<Products> products = null;
        if (name == null || name.isEmpty()) {
            products = productsService.list(currentPage, pageSize);
        } else {
            products = productsService.findByName(currentPage, pageSize, name);
            model.addAttribute("searchName", name);
        }


        model.addAttribute("products", products);
        model.addAttribute("requestURI", httpServletRequest.getRequestURI());
        return "classify/products";
    }

    @PostMapping("save")
    public String save(@Valid ProductWithModelDTO pwm, Model model, BindingResult result) {
        if (result.hasErrors()) {
            model.addAttribute("error", result);
            return "classify/products";
        }

        productsService.save(pwm);
        return "redirect:/products";
    }

    @GetMapping("delete/{id}")
    public String delete(@PathVariable String id) {
        productsService.delete(id);
        return "redirect:/products";
    }
}
